<template>
  <div>
    <el-row :gutter="6">
      <el-card>
        <el-row style="font-size: 10px;margin-bottom: 5px">
          <el-col :span="4">
            <el-button
              size="mini"
              type="primary"
              @click="batchDeleteInstockGoods()"
              >批量删除</el-button
            >
          </el-col>
          <el-col :span="20" class="text-right">
            <el-button-group>
              <el-button
                class="text-right"
                size="mini"
                type="primary"
                @click="toBatchGoodsToInStock()"
                >生成批次入库</el-button
              >

              <el-button
                size="mini"
                type="primary"
                @click="toViewAllTmpInStockGoods()"
                >查看入库日志</el-button
              >
            </el-button-group>
          </el-col>
        </el-row>
      </el-card>
    </el-row>
    <el-card :span="15" style="margin-top: 5px">
      <el-table
        :data="instockData"
        style="width: 100%"
        size="mini"
        @selection-change="handleSelectionChange2"
      >
        <el-table-column type="selection" width="30"> </el-table-column>
        <el-table-column type="index" label="序号" :index="indexMethod">
        </el-table-column>
        <el-table-column property="orderNo" label="订单号"> </el-table-column>
        <el-table-column
          property="customerName"
          label="客户"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column property="boxNo" label="箱号" width="220">
        </el-table-column>
        <el-table-column property="length" label="长" width="100">
        </el-table-column>
        <el-table-column property="width" label="宽" width="100">
        </el-table-column>
        <el-table-column property="height" label="高" width="100">
        </el-table-column>
        <el-table-column property="volume" label="体积" width="100">
        </el-table-column>
        <el-table-column property="weight" label="重量" width="100">
        </el-table-column>
        <el-table-column
          property="chargeWeight"
          label="计费重"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column label="件数" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.curCount }} - {{ scope.row.totalCount }}
          </template>
        </el-table-column>
        <el-table-column
          property="customerChannelName"
          label="入库渠道"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column property="cdate" label="时间" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row.id, scope.row, scope.$index)"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      title="入库日志"
      :visible.sync="boosyn"
      style="height: 650px;width: auto; overflow: auto"
    >
      <el-row>
        <el-col :span="3">
          <el-button type="primary" size="mini" @click="batchOp(0)"
            >批量推送</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-button type="primary" size="mini" @click="batchOp(1)"
            >批量删除</el-button
          >
        </el-col>
      </el-row>
      <el-table
        ref="multipleTable"
        :data="instockList"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection"> </el-table-column>
        <el-table-column prop="boxNo" label="箱号"> </el-table-column>
        <el-table-column prop="clearanceNo" label="外箱号"> </el-table-column>
        <el-table-column prop="length" label="长"> </el-table-column>
        <el-table-column prop="width" label="宽"> </el-table-column>
        <el-table-column prop="height" label="高"> </el-table-column>
        <el-table-column prop="weight" label="重量"> </el-table-column>
        <el-table-column prop="cdate" label="创建时间" show-overflow-tooltip>
        </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="rePushTempGoods(scope.row.id, scope.row, scope.$index)"
              >再次推送</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="deleteTempGoods(scope.row.id, scope.row, scope.$index)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="boosyn = false">取消</el-button>
        <!-- <el-button type="primary" @click="">确定</el-button> -->
      </span>
    </el-dialog>

    <el-dialog
      title="批次入库订单信息"
      :visible.sync="booBatch"
      style="height: 650px;width: auto; overflow: auto"
    >
      <el-table
        ref="multipleTable"
        :data="orderRelateInfoList"
        tooltip-effect="dark"
        style="width: 100%"
        default-expand-all
        :cell-style="changeCellStyle"
        @selection-change="handleSelectionChange1"
      >
        <el-table-column type="selection"> </el-table-column>
        <el-table-column prop="warnTips" type="expand">
          <template slot-scope="scope" style="width: 100%;">
            <span style="padding-left: 40px;color: #909399;">{{
              scope.row.warnTips
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="orderNo" label="订单号"> </el-table-column>
        <el-table-column prop="customerNameShort" label="客户">
        </el-table-column>
        <el-table-column prop="count" label="应入" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="acCount" label="实入" show-overflow-tooltip>
        </el-table-column>
        <el-table-column
          prop="finalCalData"
          label="计费数量"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column label="备注" prop="sysRemark">
          <template slot-scope="scope">
            <el-input v-model="scope.row.sysRemark" size="mini"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="batchSaveGoodsToInStock"
          v-loading.fullscreen.lock="fullscreenLoading"
          >保存</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { ajax } from "@/store/yg/common/utils";
import axios from "axios";
import * as constant from "@/store/yg/common/constant";

export default {
  components: {},
  props: ["robotNum"],
  data() {
    return {
      fullscreenLoading: false,
      instockData: [],
      boosyn: false,
      instockList: [],
      multipleSelection: [],
      multipleSelection1: [],
      multipleSelection2: [],
      booBatch: false,
      waybillNo: "",
      orderRelateInfoList: [
        {
          orderNo: "",
          customerNameShort: "",
          count: "",
          acCount: "",
          finalCalData: "",
          warnTips: "",
          sysRemark: "",
          robotNum: ""
        }
      ]
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    this.manageAutoInStockGoods();
  },
  created() {
    // 页面创建生命周期函数
    this.initWebSocket();
  },
  destroyed: function() {
    // 离开页面生命周期函数
    this.websocketclose();
  },
  methods: {
    indexMethod(index) {
      return this.instockData.length - index;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSelectionChange1(val) {
      this.multipleSelection1 = val;
    },
    handleSelectionChange2(val) {
      this.multipleSelection2 = val;
    },
    selectWaybillNo: function(val) {
      console.log(val);
    },
    initWebSocket: function() {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      // + ;
      this.websock = new WebSocket(
        //constant.API_SERVER.replace("http","ws").substring(0,constant.API_SERVER.indexOf(":"))+":8409/warehouse/websocket/1"
        constant.API_SERVER.replace("http", "ws") +
          "/warehouse/websocket/" +
          this.robotNum
      );
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onclose = this.websocketclose;
    },
    websocketonopen: function() {
      console.log("WebSocket连接成功");
    },
    websocketonerror: function() {
      console.log("WebSocket连接发生错误");
    },
    websocketonmessage: function(e) {
      let autoData = JSON.parse(e.data);
      this.instockData.unshift(autoData); //[JSON.parse(e.data),...this.instockData];
      /*if (this.waybillNo&&this.waybillNo != autoData.orderNo){
          this.toBatchGoodsToInStockCheck(this.waybillNo,autoData);
        }
        if (!this.waybillNo){
          this.waybillNo = autoData.orderNo;
        }*/
    },
    websocketclose: function(e) {
      console.log("connection closed (" + e + ")");
    },

    manageAutoInStockGoods() {
      ajax("queryAllList", { robotNum: this.robotNum }).then(
        res => {
          console.log(res);
          if (!res.code) {
            this.instockData = res;
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    handleDelete(id, row, i) {
      this.$confirm("此操作是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          ajax("delete", { id: id }).then(
            res => {
              console.log(res);
              if (res.code == 200) {
                this.$message.success("删除成功");
                this.instockData.splice(i, 1);
              } else {
                if (res.message) {
                  this.$message.error(res.message);
                } else {
                  this.$message.error("删除失败");
                }
              }
            },
            error => {
              console.log(error);
              this.$message.error("保存失败，" + error);
            }
          );
        })
        .catch(() => {});
    },
    batchDeleteInstockGoods() {
      var ids = "";
      for (var i of this.multipleSelection2) {
        ids += i.id + ",";
      }
      if (ids.indexOf(",") > -1) {
        ids = ids.substring(0, ids.length - 1);
      } else {
        this.$message.error("请先选择数据");
        return;
      }
      this.$confirm("此操作是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          ajax("batchDeleteInstockGoods", { ids: ids }).then(
            res => {
              console.log(res);
              if (res.code == 200) {
                this.$message.success("删除成功");
                this.manageAutoInStockGoods();
              } else {
                if (res.message) {
                  this.$message.error(res.message);
                } else {
                  this.$message.error("删除失败");
                }
              }
            },
            error => {
              console.log(error);
              this.$message.error("保存失败，" + error);
            }
          );
        })
        .catch(() => {});
    },
    toViewAllTmpInStockGoods() {
      ajax("toViewAllTmpInStockGoods", { robotNum: this.robotNum }).then(
        res => {
          console.log(res);
          if (res.code == 200) {
            this.instockList = res.data;
            this.boosyn = true;
          } else {
            if (res.message) {
              this.$message.error(res.message);
            } else {
              this.$message.error("异常");
            }
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    batchOp(obj) {
      var ids = "";
      for (var i of this.multipleSelection) {
        ids += i.id + ",";
      }
      if (ids.indexOf(",") > -1) {
        ids = ids.substring(0, ids.length - 1);
      } else {
        this.$message.error("请先选择数据");
        return;
      }
      this.$confirm("此操作是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          var url = "";
          if (obj == 0) {
            url = "batchSaveAddInStockGoods";
          } else {
            url = "batchDeleteTempGoods";
          }
          ajax(url, { ids: ids }).then(
            res => {
              console.log(res);
              if (res.code == 200) {
                this.$message.success("操作成功");
                if (obj != 0) {
                  this.toViewAllTmpInStockGoods();
                }
              } else {
                if (res.message) {
                  this.$message.error(res.message);
                } else {
                  this.$message.error("操作失败");
                }
              }
            },
            error => {
              console.log(error);
            }
          );
        })
        .catch(() => {});
    },
    rePushTempGoods(id, row, i) {
      if (!id) {
        this.$message.error("该数据不存在");
        return;
      }
      ajax("batchSaveAddInStockGoods", { ids: id }).then(
        res => {
          console.log(res);
          if (res.code == 200) {
            this.$message.success("已推送");
          } else {
            if (res.message) {
              this.$message.error(res.message);
            } else {
              if (res.message) {
                this.$message.error(res.message);
              } else {
                this.$message.error("推送失败");
              }
            }
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    deleteTempGoods(id, row, i) {
      if (!id) {
        this.$message.error("该数据不存在");
        return;
      }
      ajax("deleteTempGoodsById", { id: id }).then(
        res => {
          console.log(res);
          if (res.code == 200) {
            this.instockList.splice(i, 1);
            this.$message.success("已删除");
          } else {
            if (res.message) {
              this.$message.error(res.message);
            } else {
              this.$message.error("删除失败");
            }
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    toBatchGoodsToInStock() {
      ajax("toBatchGoodsToInStock", { robotNum: this.robotNum }).then(
        res => {
          console.log(res);
          if (res.code == 200) {
            this.booBatch = true;
            var array = res.data;
            if (array) {
              for (var str of array) {
                str["robotNum"] = this.robotNum;
              }
            }
            this.orderRelateInfoList = array;
          } else {
            if (res.message) {
              this.$message.error(res.message);
            } else {
              this.$message.error("查询异常");
            }
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    changeCellStyle(row, column, rowIndex, columnIndex) {
      if (row.row.count != row.row.acCount) {
        return "color: red"; // 修改的样式
      } else {
        return "";
      }
    },
    /*toBatchGoodsToInStockCheck(waybillStr,autoData) {
        ajax("toBatchGoodsToInStock", { robotNum: this.robotNum }).then(
          res => {
            console.log(res);
            if (res.code == 200) {
              for (var str of res.data){
                if (str==waybillStr){
                  if (str.count!=str.acCount){
                    this.$message.error(this.waybillNo+"应入"+str.count+"不等于实入"+str.acCount+",请检查!")
                  } else {
                    this.waybillNo = autoData.orderNo;
                  }
                }
              }
            } else {
              this.$message.error("查询异常");
            }
          },
          error => {
            console.log(error);
          }
        );
      },*/
    async batchSaveGoodsToInStock() {
      if (this.multipleSelection1.length == 0) {
        this.$message.error("请先选择数据");
        return;
      }
      this.fullscreenLoading = true;
      let attrs = {};
      attrs["headers"] = {
        "YG-UNIQUE-KEY": "save_instock_info_" + new Date().getTime()
      };
      const res = await ajax("batchSaveGoodsToInStock", {
        instockGoodsList: this.multipleSelection1
      },attrs);
      this.fullscreenLoading = false;
      console.log(res);
      if (res.code == 200) {
        this.$message.success("保存成功");
        this.booBatch = false;
        this.manageAutoInStockGoods();
      } else {
        this.$message.error(res.message);
      }

      // console.log(this.multipleSelection1);

      // var selectionList = [];
      // var selectionObj = {};
      /* for (var i=0;i<this.multipleSelection1.length;i++){
              var selectionObj = {};
              selectionObj.orderNo = this.multipleSelection1[i].orderNo;
              selectionObj.sysRemark = this.multipleSelection1[i].sysRemark;
              selectionList.push(selectionObj);
            }*/
      // ajax("batchSaveGoodsToInStock", {
      //   instockGoodsList: this.multipleSelection1
      // }).then(
      //   res => {
      //     console.log(res);
      //     if (res.code == 200) {
      //       row.remove();
      //       this.$message.success("");
      //     } else {
      //       this.$message.error("");
      //     }
      //   },
      //   error => {
      //     console.log(error);
      //   }
      // );
    }
  }
};
</script>
<style>
.green {
  color: red;
}
</style>
